package org.example.utils;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.net.URLDecoder;
import java.util.HashSet;

public class AnnoUtil {


    private static void setValue(Object bean, String fieldName, Object value) throws Exception {
        Field privateVar = bean.getClass().getDeclaredField(fieldName);
        privateVar.setAccessible(true);
        privateVar.set(bean, value);
    }

    private static Object getValue(Object bean, String fieldName) throws Exception {
        Field privateVar = bean.getClass().getDeclaredField(fieldName);
        privateVar.setAccessible(true);
        return privateVar.get(bean);
    }

    public static HashSet<String> getReferenceList(Class<?> cinfigClass, String packageName) throws IOException {
        HashSet<String> classList = new HashSet<>();
        String suffixPath = replaceAllChar(packageName, '.', '/');


        String path = cinfigClass.getResource("").getPath();
        path = URLDecoder.decode(path);
        String classRootPath = path.substring(0, path.indexOf(suffixPath) + suffixPath.length());
        File f = new File(classRootPath);
        getSubFile(f.listFiles(), classList);


        HashSet<String> referenceList = new HashSet<>();

        String suffixPkg = replaceAllChar(packageName, '.', '\\');
        for (String s : classList) {
            if (!s.endsWith(".class")) {
                continue;
            }
            int i = s.indexOf(suffixPkg);
            String fullPath = s.substring(i);
            fullPath = fullPath.replaceAll(".class", "");
            String reference = replaceAllChar(fullPath, '\\', '.');
            referenceList.add(reference);
        }
        return referenceList;
    }


    public static void getSubFile(File[] files, HashSet<String> classList) {
        for (File f : files) {
            if (f.isFile()) {
                classList.add(f.getPath());
            } else {
                getSubFile(f.listFiles(), classList);
            }
        }
    }

    public static String replaceAllChar(String oldString, char oldChar, char newChar) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < oldString.length(); i++) {
            char c = oldString.charAt(i);
            if (c == oldChar) {
                sb.append(newChar);
            } else {
                sb.append(c);
            }
        }
        return sb.toString();
    }
}
